package org.meruvian.yama.service;

import java.util.Date;

import javax.inject.Inject;

import org.apache.commons.lang.StringUtils;
import org.meruvian.yama.Item;
import org.meruvian.yama.dao.ItemDomain;
import org.meruvian.yama.persistence.EntityListWrapper;
import org.meruvian.yama.persistence.LogInformation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class ItemServiceImpl implements ItemService{
	
	@Inject
	private ItemDomain itemDomain;

	@Transactional
	public Item saveItem(Item item) {
		// TODO Auto-generated method stub
		if (StringUtils.isBlank(item.getId())) {
			item.setId(null);
			item.setLogInformation(new LogInformation());

			itemDomain.persist(item);
		} else {
			Item s = itemDomain.findById(item.getId());
			s.setName(item.getName());
			s.setDescription(item.getDescription());

			s.getLogInformation().setUpdateDate(new Date());

			return s;
		}
		return item;
	}

	public Item getItemsById(String id) {
		// TODO Auto-generated method stub
		return itemDomain.findById(id);
	}

	public EntityListWrapper<Item> findItems(String name, String description,
			String orderby, String order, int max, int page) {
		// TODO Auto-generated method stub
		return itemDomain.findItems(name, description, orderby, order,
				max, page, "AND");
	}

	public EntityListWrapper<Item> findItems(String field, int max,
			String orderBy, String order, int page) {
		// TODO Auto-generated method stub
		return itemDomain.findItems(field, field, orderBy, order, max,
				page, "OR");
	}

}
